package com.unitd.comm.web;

import com.unitd.frame.sso.annotation.Action;
import com.unitd.frame.sso.annotation.Permission;
import com.unitd.frame.springweb.upload.base.UploadFile;
import com.unitd.frame.springweb.upload.base.UploadMsg;
import com.unitd.frame.springweb.upload.multipart.UploadMultipartRequest;
import org.apache.commons.httpclient.util.DateUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;

/**
 * @desc 上传服务 View 端控制器类,与头像上传控件:http://www.fullavatareditor.com/index.html 匹配管理
 * @filename BaseController.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2016/10/4
 */
@Controller
@RequestMapping("/upload")
public class UploadController extends BaseController {

	/* 限制最大上传 3M */
	private final static int MAX_POST_SIZE = 3 * 1024 * 1024;

	/**
	 * @return 上传成功与否消息
	 * @desc 上传文件; 默认情况下,上传后的文件保存在当前项目的根目录下(后续更改为保存到分布式文件服务中去)
	 */
	@ResponseBody
	@Permission(action = Action.Skip)
	@RequestMapping(value = "/file", method = RequestMethod.POST)
	public String file() {
		UploadMsg msg = new UploadMsg();
		try {
			// 获取前端上传的文件对象信息
			UploadMultipartRequest umr = new UploadMultipartRequest(request, getSaveDir(), MAX_POST_SIZE);
			umr.setFileHeaderExts("ffd8ff.jpg"); 					// 设置文件头
			umr.upload(); 											// 上传

			Enumeration<?> files = umr.getFileNames(); 				// 上传文件列表
			while (files.hasMoreElements()) {
				String name = (String) files.nextElement();
				UploadFile cf = umr.getUploadFile(name);
				if (cf != null) {
					// 上传成功
					if (cf.isSuccess()) {
						msg.setSuccess(true);
						msg.setUrl(cf.getFileUrl());
						msg.setSize(cf.getSize());
						System.out.println("上传文件地址：" + msg.getUrl());
					}
					msg.setMsg(cf.getUploadCode().desc());
				}
			}
		} catch (IOException e) {
			logger.error("上传文件出错[" + e.getMessage() + "]");
		}
		return toJson(msg);
	}

	/**
	 * @desc 设置上传文件的存放目录(默认情况下, 上传后的文件保存在当前项目的根目录下; 后续更改为保存到分布式文件服务中去)
	 * @return
	 */
	private static String getSaveDir() {
		StringBuffer filePath = new StringBuffer(System.getProperty("user.dir"));
		filePath.append(File.separator);
		filePath.append(DateUtil.formatDate(new Date(), "yyyy"));
		filePath.append(File.separator);
		File file = new File(filePath.toString());
		if (!file.exists()) {
			file.mkdirs();
		}
		return file.getPath();
	}
}